package com.niiwoo.civet.account.service.local.withholdProtocol;

import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.niiwoo.civet.account.dao.entity.WithholdProtocolApplyOrder;
import com.niiwoo.civet.account.dao.entity.WithholdProtocolConfirmOrder;
import com.niiwoo.tripod.lanmao.component.LanMaoDirectService;
import com.niiwoo.tripod.lanmao.enums.LanMaoErrorCodeEnum;
import com.niiwoo.tripod.lanmao.request.ProtocolSignConfirmRequest;
import com.niiwoo.tripod.lanmao.request.ProtocolSignQueryRequest;
import com.niiwoo.tripod.lanmao.request.ProtocolSignRequest;
import com.niiwoo.tripod.lanmao.response.ProtocolSignConfirmResponse;
import com.niiwoo.tripod.lanmao.response.ProtocolSignQueryResponse;
import com.niiwoo.tripod.lanmao.response.ProtocolSignResponse;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * 协议支付调用
 */
@Slf4j
public abstract class WithholdProtocolHandler {

    @Autowired
    private LanMaoDirectService lanMaoDirectService;

    /**
     * 自动扫描时间
     * 当前时间，向前推 scanTime 毫秒 10000
     */
    protected int scanTime = 10 ;

    /**
     * 设置走主库
     */
    protected void setMasterRouteOnly(){
        if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManager.getInstance().setMasterRouteOnly();
        }
    }
    /**
     * 协议支付签约接口 请求
     * @param withholdProtocolApplyOrder
     */
    protected WithholdProtocolApplyOrder protocolSign(WithholdProtocolApplyOrder withholdProtocolApplyOrder){
        ProtocolSignResponse protocolSignResponse = null ;
        WithholdProtocolApplyOrder applyOrderUpdate = new WithholdProtocolApplyOrder();
        applyOrderUpdate.setId(withholdProtocolApplyOrder.getId());
        try{
            ProtocolSignRequest request = new ProtocolSignRequest();
            request.setRequestNo(withholdProtocolApplyOrder.getRequestNo());
            request.setPlatformUserNo(withholdProtocolApplyOrder.getPlatformUserNo());
            request.setExpectPayCompany(withholdProtocolApplyOrder.getExpectPayCompany());
            CompletableFuture<ProtocolSignResponse> response = lanMaoDirectService.applyWithholdProtocol(request);
            protocolSignResponse = response.get();
            log.info("协议支付-申请签约 返回结果:{}", JSON.toJSONString(protocolSignResponse));

            withholdProtocolApplyOrder.setUpdateTime(new Date());
            if(protocolSignResponse.isSuccess()){
                applyOrderUpdate.setStatus(Status.SUCCESS.getCode());
                applyOrderUpdate.setPrepareId(protocolSignResponse.getPrepareId());
                return applyOrderUpdate;
            }else{
                /*if (!LanMaoErrorCodeEnum.REQUEST_NO_REPEAT.getCode().equals(protocolSignResponse.getErrorCode())
                        && !LanMaoErrorCodeEnum.SYSTEM_ERROR.getCode().equals(protocolSignResponse.getErrorCode())){*/

                applyOrderUpdate.setStatus(Status.FAILURE.getCode());
                applyOrderUpdate.setChannelErrorCode(protocolSignResponse.getChannelErrorCode());
                applyOrderUpdate.setChannelErrorMessage(protocolSignResponse.getChannelErrorMessage());
                applyOrderUpdate.setErrorCode(protocolSignResponse.getErrorCode());
                applyOrderUpdate.setErrorMessage(protocolSignResponse.getErrorMessage());
                return applyOrderUpdate;
            }

        }catch (Exception e){
            log.error("协议支付签约接口异常，订单号：{}",JSON.toJSONString(withholdProtocolApplyOrder),e);
            applyOrderUpdate.setStatus(Status.INIT.getCode());
            applyOrderUpdate.setErrorMessage(ErrorCode.CONNECT.getDesc());
            return applyOrderUpdate;
        }
    }


    /**
     * 协议支付签约确认接口 请求
     * @param withholdProtocolConfirmOrder
     */
    protected WithholdProtocolConfirmOrder confirmProtocolSign(WithholdProtocolConfirmOrder withholdProtocolConfirmOrder){
        ProtocolSignConfirmResponse protocolSignConfirmResponse ;
        WithholdProtocolConfirmOrder confirmOrderUpdate = new WithholdProtocolConfirmOrder();
        confirmOrderUpdate.setId(withholdProtocolConfirmOrder.getId());
        confirmOrderUpdate.setApplyOrderId(withholdProtocolConfirmOrder.getApplyOrderId());
        confirmOrderUpdate.setPrepareId(withholdProtocolConfirmOrder.getPrepareId());
        try{
            ProtocolSignConfirmRequest request = new ProtocolSignConfirmRequest();
            request.setPrepareId(withholdProtocolConfirmOrder.getPrepareId());
            request.setVerifyCode(withholdProtocolConfirmOrder.getVerifyCode());
            request.setRequestNo(withholdProtocolConfirmOrder.getRequestNo());
            CompletableFuture<ProtocolSignConfirmResponse> response = lanMaoDirectService.confirmWithholdProtocol(request);
            protocolSignConfirmResponse = response.get();
            log.info("协议支付-确认 返回结果:{}", JSON.toJSONString(protocolSignConfirmResponse));
            withholdProtocolConfirmOrder.setUpdateTime(new Date());

            if(protocolSignConfirmResponse.isSuccess()){
                if(Status.SUCCESS.name().equals(protocolSignConfirmResponse.getProtocolStatus())){
                    confirmOrderUpdate.setStatus(Status.SUCCESS.getCode());
                }else{
                    log.info("协议支付-确认 签约处理失败，id:{},requestNO:{}",withholdProtocolConfirmOrder.getId(),withholdProtocolConfirmOrder.getRequestNo());
                    confirmOrderUpdate.setStatus(Status.FAILURE.getCode());
                    confirmOrderUpdate.setChannelErrorCode(protocolSignConfirmResponse.getChannelErrorCode());
                    confirmOrderUpdate.setChannelErrorMessage(protocolSignConfirmResponse.getChannelErrorMessage());
                    confirmOrderUpdate.setErrorCode(protocolSignConfirmResponse.getErrorCode());
                    confirmOrderUpdate.setErrorMessage(protocolSignConfirmResponse.getErrorMessage());
                }
            }else{
                log.info("协议支付-确认 签约受理失败，id:{},requestNO:{}",withholdProtocolConfirmOrder.getId(),withholdProtocolConfirmOrder.getRequestNo());
                confirmOrderUpdate.setStatus(Status.FAILURE.getCode());
                confirmOrderUpdate.setChannelErrorCode(protocolSignConfirmResponse.getChannelErrorCode());
                confirmOrderUpdate.setChannelErrorMessage(protocolSignConfirmResponse.getChannelErrorMessage());
                confirmOrderUpdate.setErrorCode(protocolSignConfirmResponse.getErrorCode());
                confirmOrderUpdate.setErrorMessage(protocolSignConfirmResponse.getErrorMessage());
            }

         }catch (Exception e){
            log.error("协议支付签约确认接口异常，确认订单：{}",JSON.toJSONString(withholdProtocolConfirmOrder),e);
            confirmOrderUpdate.setStatus(Status.INIT.getCode());
            confirmOrderUpdate.setErrorMessage(ErrorCode.CONNECT.getDesc());
         }
         return confirmOrderUpdate;
    }

    /**
     * 协议支付签约信息查询
     */
    protected ProtocolSignQueryResponse queryProtocolSign(ProtocolSignQueryRequest request){
        ProtocolSignQueryResponse protocolSignQueryResponse ;
        try{
            CompletableFuture<ProtocolSignQueryResponse> response = lanMaoDirectService.getWithholdProtocolResult(request);
            protocolSignQueryResponse = response.get();
            log.info("协议支付-查询 返回结果:{}", JSON.toJSONString(protocolSignQueryResponse));
            return protocolSignQueryResponse;
         }catch (Exception e){
            log.error("协议支付签约信息查询异常，platformUserNo:{}",request.getPlatformUserNo());
            protocolSignQueryResponse = new ProtocolSignQueryResponse();
            protocolSignQueryResponse.setStatus("FAILURE");
            protocolSignQueryResponse.setCode(ErrorCode.CONNECT.getCode());
            protocolSignQueryResponse.setErrorMessage(ErrorCode.CONNECT.getDesc());
            return protocolSignQueryResponse;
         }
    }


    @AllArgsConstructor
    @Getter
    public enum Status {
        INIT((byte)1,"处理中"),
        SUCCESS((byte)2,"成功"),
        FAILURE((byte)3,"失败"),
        ;
        private Byte code;
        private String desc;
    }

    @AllArgsConstructor
    @Getter
    public enum Expire {
        OVERDUE(0,"失效"),
        EFFECTIVE(1,"有效")
        ;
        private Integer code;
        private String desc;
    }

    @AllArgsConstructor
    @Getter
    public enum FromSource {
        ONLINE((byte)1,"线上短信签约"),
        OFFLINE_IMPORT((byte)2,"存量用户线下导入签约")
        ;
        private Byte code;
        private String desc;
    }

    @AllArgsConstructor
    @Getter
    public enum ErrorCode {
        CONNECT((byte)99,"网络连接异常");

        private Byte code;
        private String desc;
    }
}


